<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        // 如果是游客, 跳转到登录页面或者返回无权限
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }
        /**
         * 获取当前用户
         * @var User
         */
        $user = Auth::user();
        // 获取URL前缀
        $prefix = $request->route()->getPrefix();
        //如果是api, 继续访问
        if($prefix === '/api'){
            return $next($request);
        }
        // 如果是管理员, 跳转到管理页面
        if($user->isAdmin()){
            if($prefix !== '/admin'){
                return redirect('admin');
            }
            return $next($request);
        }
        // 如果是库存管理员, 跳转到库存页面
        if($user->isManager()){
            if($prefix !== '/manager'){
                return redirect('manager');
            }
            return $next($request);
        }

        abort(404);
    }
}
